package com.jwm.power.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.net.URLDecoder;

/**
 * @Auther: chenjinbo
 * @Date: 2019/5/20 09:20
 * @Description:
 */
@SpringBootConfiguration
public class MyWebConfig extends WebMvcConfigurerAdapter {
    @Value("${file.avatarPath}")
    private String avatarPath;

    @Value("${file.logoPath}")
    private String logoPath;

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        try {
            //获取项目根目录
            String serverPath = URLDecoder.decode(ResourceUtils.getURL("").getPath(), "UTF-8");


            /*
             *这是添加的配置，表示将/avatar/..映射到D:/data/images/avatar/目录
             *这样在上传图片时将路径设置为：D:/data/images/avatar/，在访问上传的图片时如：http://ip:port/avatar/xxx.jpg就能访问到图片了。
             */
            //registry.addResourceHandler("/avatar/**").addResourceLocations("file:" + serverPath + avatarPath);
            //通过http://ip:port/logo.png即可访问到D:/data/images/logo.png
//            registry.addResourceHandler("/logo.png").addResourceLocations("file:" + serverPath + logoPath + "logo.png");
            //访问系统或APP上传的附件、图片、视频等
            registry.addResourceHandler("/upload/**").addResourceLocations("file:" + serverPath + uploadPath);
//            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

            super.addResourceHandlers(registry);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
